<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div>
        图片上传：
        <input type="file" name="file" value="" id="input-file" accept="image/png,image/jpeg,image/gif,image/jpg">
    </div>
    <div>
        图片回显：
        <img id="upload-file" src="" alt="" width="300">
    </div>

    <!--th:fragment定义代码块标识-->
<!--    <footer th:fragment="copy">-->
<!--        2021 The FastDFS System Power by Tony-->
<!--    </footer>-->

<!--    <div th:replace="fragment::copy"></div>-->

    <!--th:insert是在div中插入代码块，即多了一层div-->
        <div>
            <footer>
                @2021 The FastDFS System Power by Tony
            </footer>
        </div>

<!-- 使用thymeleaf模板引入web下的静态资源 -->
<script charset="utf-8" type="text/javascript" th:src="@{/lib/jquery-3.5.1.min.js}"></script>
<script charset="utf-8" type="text/javascript">

$('#input-file').on("change", function() {

    var file = this.files[0];
    var formData = new FormData();
    formData.append('file', file);
    // 开始上传
    fileUpload("/upload", formData);

    // 测试读取图片(本地显示)
    var fileReader = new FileReader();
    fileReader.readAsDataURL(file);
    fileReader.onloadend = function(fEvent){
        var src = fEvent.target.result;
        console.log(src);
        $("#upload-file").attr("src", src);
    }
});

function fileUpload(url, formData){
    $.ajax({
        url: url,
        type: 'POST',
        cache: false,
        data: formData,
        processData: false,
        contentType: false,
        dataType: "json",
        success: function (res) {
            console.log(res);
        },
        error: function (xhr, type, errorThrown) {
            console.log("照片上传失败")
        }
    });
}
</script>

</body>
</html>
